import Serves from "@renderer/utils/requestNew";
import { generateFilterFunc } from "@renderer/hooks/useEvents";

export const useDataSource = async (dataSourceInfo, layoutItemRequest) => {
  return new Promise(async (resolve, reject) => {
    const { serviceUrl, tokenVal } = dataSourceInfo;

    let tokenParamJson = JSON.parse(dataSourceInfo.tokenParamJson);
    let token = "";
    let request = new Serves(tokenParamJson.baseUrl).instance;
    if (!tokenVal) {
      try {
        if (tokenParamJson.ifFormData) {
          let formdata = new FormData();
          for (let key in tokenParamJson.data) {
            formdata.append(key, tokenParamJson.data[key]);
          }
          tokenParamJson.data = formdata;
        }
        let res: any = await request({
          ...tokenParamJson,
          url: tokenParamJson.url,
        });
        if (res.code == 200) {
          token = generateFilterFunc(
            tokenParamJson.filterMethods,
            res.data,
            res
          )();
        } else {
          ElMessage.error("数据源获取token失败:" + res.msg || res.message);
        }
      } catch (error) {
        token = "";
        ElMessage.error("数据源获取token失败:" + error);
      }
    } else {
      token = tokenVal;
    }

    if (token) {
      switch (tokenParamJson.potition.type) {
        case "Header":
          layoutItemRequest.headers[tokenParamJson.potition.params] = token;
          break;
        case "BodyParams":
          layoutItemRequest.data[tokenParamJson.potition.params] = token;
          break;
        case "BodyFormData":
          // if (!(layoutItemRequest.data instanceof FormData)) return;
          // (layoutItemRequest.data as FormData).append(
          //   tokenParamJson.potition.params,
          //   token
          // );
          layoutItemRequest.data[tokenParamJson.potition.params] = token;
          break;
        default:
          break;
      }
    }
    layoutItemRequest.baseUrl = serviceUrl;
    // console.log("layoutItemRequest", layoutItemRequest);
    resolve(layoutItemRequest);
  });
};
